import 'package:valovault_reminder/common/ui/val_ui_kit_btn.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_base_colors.dart';
import 'package:valovault_reminder/common/ui/val_ui_kit_dialog_impl.dart';
import 'package:valovault_reminder/common/ui/val_base_ui_kit_root.dart';
import 'package:valovault_reminder/common/ui/val_auto_fit_screen_size.dart';
import 'package:valovault_reminder/common/ui/val_common_text.dart';
import 'package:valovault_reminder/common/util/val_router_manager.dart';
import 'package:valovault_reminder/pages/web/val_webview_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import '../../common/config/val_assets_name.dart';
import '../../common/config/val_client_url_path.dart';
import '../../common/util/val_app_state_tool.dart';
import '../../common/util/val_logger_manager.dart';
import '../../common/util/val_device_info_loader.dart';
import '../../http/val_dio_fetch_kit.dart';

class ValReminderLoginPage extends StatefulWidget {
  const ValReminderLoginPage({super.key});

  @override
  State<ValReminderLoginPage> createState() => _ValReminderLoginPageState();
}

class _ValReminderLoginPageState extends State<ValReminderLoginPage> {

  ValLoginPrivateView logic =  ValLoginPrivateView();

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder(
      valueListenable: logic.flag,
      builder: (BuildContext context, bool value, Widget? child) {
        return ValBaseUIKitRoot(
          Stack(
            children: [
              Image.asset('${ValAssetsName.ASSETS_LOGIN}val_login_ground.png',
                height: double.infinity,
                width: double.infinity,
                fit: BoxFit.fitWidth,),
              Positioned(bottom: 10.w,
                child: Container(
                    width: ValAutoFitScreenSize.screenWidth,
                    padding: EdgeInsets.only(left: 24.w, right: 24.w),
                    child: Column(
                      mainAxisAlignment:  MainAxisAlignment.center,
                      children: [
                        _buildFastLoginLogin(),
                        SizedBox(height: 30.w,),
                        _buildAppleLoginLogin(),
                        SizedBox(height: 30.w,),
                        _buildPolicy(),
                        SizedBox(height: 40.w,),
                        // SafeArea(bottom: true, child: SizedBox())
                      ],
                    )),
              ),
            ],
          ),
        );
      }
    );
  }

  Widget _buildFastLoginLogin() {
    return ValUIKitBtn(Container(
      height: 61.w,
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [
            Color(0xFFF6CD21),
            Color(0xFFE9A81A),
          ],
        ),
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: Row(
        children: [
          SizedBox(width: 36.w,),
          Image.asset('${ValAssetsName.ASSETS_LOGIN}val_login_fast_btn.png',
            height: 26.w,
            width: 26.w,
            fit: BoxFit.fill,),
          // SizedBox(width: 20.w,),
          const Expanded(child: ValCommonText.oneLine('Fast Login', 21.67,
            Color(0xFF333333),
            fontWeight: FontWeight.w600,
            textAlign:  TextAlign.center,)),
          SizedBox(width: 50.w,),
        ],
      ),
    ), () => logic.onTapFastLogin());
  }

  Widget _buildAppleLoginLogin() {
    return ValUIKitBtn(Container(
      height: 61.w,
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
          colors: [
            Color(0xFFE5FF48),
            Color(0xFF7BCD4A),
          ],
        ),
        borderRadius: BorderRadius.circular(10.w),
      ),
      child: Row(
        children: [
          SizedBox(width: 36.w,),
          Image.asset('${ValAssetsName.ASSETS_LOGIN}val_login_apple_btn.png',
            height: 26.w,
            width: 26.w,
            fit: BoxFit.fill,),
          // SizedBox(width: 20.w,),
          const Expanded(child: ValCommonText.oneLine('Sign in with Apple', 21.67,
            ValUIKitBaseColors.black,
            fontWeight: FontWeight.w600,
            textAlign:  TextAlign.center,)),
          SizedBox(width: 50.w,),
        ],
      ),
    ), () => logic.onTapAppleLogin());
  }

  Widget _buildPolicy() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        ValUIKitBtn(Image.asset('${ValAssetsName.ASSETS_LOGIN}${logic.isSelectedPolicy ? 'val_login_agree_btn' : 'val_login_disagree_btn'}.png',
          height: 20.w,
          width: 20.w,
          fit: BoxFit.fill,),
                () => logic.onTapPrivacyBtn()),
        SizedBox(width: 8.w,),
        Column(
          crossAxisAlignment:  CrossAxisAlignment.start,
          children: [
            ValCommonText.oneLine('By using our App you agree with our', 12.w, ValUIKitBaseColors.white),
            Row(
              children: [
                ValUIKitBtn(ValCommonText.oneLine('Term of Use', 13.w,
                    ValUIKitBaseColors.white,
                    decoration: TextDecoration.underline),
                        () {
                          ValLoggerManager.stat(page: ValConfigLoggerPath.terms);
                  ValRouterManager.open(ValWebViewController(ValClientUrlPath.termsConditionUrl, title: 'Term of Use',));
                }),
                ValCommonText.oneLine(' and ', 12.w, ValUIKitBaseColors.white),
                ValUIKitBtn(ValCommonText.oneLine('Privacy Policy', 13.w,
                  ValUIKitBaseColors.white,
                  decoration: TextDecoration.underline,),
                        () {
                          ValLoggerManager.stat(page: ValConfigLoggerPath.privacy);
                          ValRouterManager.open(ValWebViewController(ValClientUrlPath.privacyUrl, title: 'Privacy Policy',));
                })
              ],
            )
          ],
        )
      ],
    );
  }
}

class ValLoginPrivateView {
  bool isSelectedPolicy = false;

  final ValueNotifier<bool> flag = ValueNotifier(false);

  void update() => flag.value = !flag.value;

  /// 隐私协议
  void onTapPrivacyBtn() {
    isSelectedPolicy = !isSelectedPolicy;
    update();
  }

  /// 快速登录
  void onTapFastLogin() async {
    if (isSelectedPolicy == false) {
      _showPrivacyView(() async {
        loginRequest();
      });
    }
    else {
      loginRequest();
    }
  }

  void loginRequest() async {
    ValLoggerManager.stat(page: ValConfigLoggerPath.quickloginPage);
    ValUIKitDialogImpl.showProgress();
    String token = await  ValDeviceInfoLoader.getDeviceId() ?? '';
    ValDioFetchKit.getInstance().postJsonWithUrl(
        ValClientUrlPath.loginUrl,
        {'oauthType': 4 ,
          'token' : token
        },
        contentType: 'application/x-www-form-urlencoded',
            (data, errorCode, message) {
          ValUIKitDialogImpl.hideProgress();
          if (errorCode == 0) {
            ValAppStateTool.saveLoginInfo(data);
            ValLoggerManager.stat(page: ValConfigLoggerPath.loginsuccess);
            ValRouterManager.gotoMain();
          }else {
            ValUIKitDialogImpl.showNoBtn(msg: message, title: 'Tip');
          }
        }, (err) {
      ValUIKitDialogImpl.showNoBtn(msg: 'Login failed', title: 'Tip');
      // CommonRoute.gotoMain();
    });
  }


  /// 苹果登录
  void  onTapAppleLogin() {
    ValLoggerManager.stat(page: ValConfigLoggerPath.applelogin);
    if (isSelectedPolicy == false) {
      _showPrivacyView((){
        SignInWithAppleButton(
          onPressed: () async {
            appleLogin();
          },
        );
      });
    }
    else {
      appleLogin();
    }

  }

  void appleLogin() async {
    // final credential = await SignInWithApple.getAppleIDCredential(
    //   scopes: [
    //     AppleIDAuthorizationScopes.email,
    //     AppleIDAuthorizationScopes.fullName,
    //   ],
    // );

    SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName
      ],
    ).then((credential) async {
      /// credential.identityToken
      ValUIKitDialogImpl.showProgress();
      String token = await ValDeviceInfoLoader.getDeviceId() ?? '';
      ValDioFetchKit.getInstance().postJsonWithUrl(
          ValClientUrlPath.loginUrl,
          { 'oauthType': 3 ,
            'token' : credential.identityToken ?? ''
          },
          contentType: 'application/x-www-form-urlencoded',
              (data, errorCode, message) {
            ValUIKitDialogImpl.hideProgress();
            if (errorCode == 0) {
              ValAppStateTool.saveLoginInfo(data);
              ValRouterManager.gotoMain();
              ValLoggerManager.stat(page: ValConfigLoggerPath.loginsuccess);
            }else {
              ValUIKitDialogImpl.showNoBtn(msg: message, title: 'Tip');
            }
          }, (err) {
        ValUIKitDialogImpl.showNoBtn(msg: 'Login failed', title: 'Tip');
      });
    }).catchError((e) {
      // ValUIKitDialogImpl.showNoBtn(msg: 'Login failed', title: 'Tip');
    });
  }

  void _showPrivacyView(Function call) {
    ValUIKitDialogImpl.showCenter(ValUserPrivacyContentView(() {
      isSelectedPolicy = true;
      call();
      update();
    }));
  }
}


class ValUserPrivacyContentView extends StatelessWidget {

  final Callback onSure;

  const ValUserPrivacyContentView(this.onSure,{super.key});

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: EdgeInsets.only(left: 30.w, right: 30.w),
        child: Center(
          child:  Container(
            height: 328.w,
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(color: Colors.white,borderRadius:  BorderRadius.circular(24.w)),
            child:  Column(
              children: [
                Container(
                  decoration: BoxDecoration(borderRadius:  BorderRadius.circular(2)),
                  clipBehavior:  Clip.hardEdge,
                  child: Image.asset('assets/images/val_logo_medium.png',
                    height: 80.w,
                    width: 80.w,
                    fit: BoxFit.fill,),
                ),
                SizedBox(height: 10.w,),
                ValCommonText.oneLine('VeloVault', 20.w, ValUIKitBaseColors.black, fontWeight:  FontWeight.bold),
                SizedBox(height: 10.w,),
                Column(
                  crossAxisAlignment:  CrossAxisAlignment.center,
                  children: [
                    ValCommonText.oneLine('By using our App you agree with our', 14.w, ValUIKitBaseColors.black),
                    SizedBox(height: 4.w,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ValUIKitBtn(ValCommonText.oneLine('Term of Use', 14.w, const Color(0xFF000000)), () => null),
                        ValCommonText.oneLine(' And ', 14.w, ValUIKitBaseColors.black),
                        ValUIKitBtn(ValCommonText.oneLine('Privacy Policy.', 14.w, const Color(0xFF000000)), () => null)
                      ],
                    )
                  ],
                ),
                SizedBox(height: 18.w,),
                _buildAgreeBtn(),
                SizedBox(height: 18.w,),
                _buildCancelBtn(),
              ],
            ),
          ),
        )
    );
  }


  Widget _buildAgreeBtn() {
    return ValUIKitBtn(Padding(
      padding: EdgeInsets.only(left: 30.w,right: 30.w),
      child: Container(
        height: 40.w,
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            colors: [
              Color(0xFFE9A81A),
              Color(0xFFF6CD21),
            ],
          ),
          borderRadius: BorderRadius.circular(20.w),
        ),
        child: Center(
          child: ValCommonText.oneLine('Agree and Continue', 12.w,
            ValUIKitBaseColors.black,
            fontWeight: FontWeight.bold,
            textAlign:  TextAlign.center,),
        ),
      ),
    ),(){
      ValUIKitDialogImpl.closeDialog();
      onSure();
    },);
  }

  Widget _buildCancelBtn() {
    return ValUIKitBtn(Padding(
      padding: EdgeInsets.only(left: 30.w,right: 30.w),
      child: Container(
        height: 40.w,
        decoration: BoxDecoration(color: const Color(0xFFF4F4F4),borderRadius: BorderRadius.circular(20.w)),
        child: Center(
          child: ValCommonText.oneLine('Cancel', 14.w,
            ValUIKitBaseColors.textLeveTwo,
            fontWeight: FontWeight.bold,
            textAlign:  TextAlign.center,),
        ),
      ),
    ),() => ValUIKitDialogImpl.closeDialog(),);
  }
}




